import { Component, OnInit,ViewChild } from '@angular/core';
import {adSystemApiUrl} from '../../../../config/api';
import {ModalDirective} from 'ngx-bootstrap';
import {HttpService} from '../../../lib/service/http.service'

@Component({
  selector: 'app-article-list',
  templateUrl: 'article-list.component.html',
  styleUrls: ['article-list.component.scss'],
  providers: []
})
export class ArticleListComponent implements OnInit {

  type: string;
  message: string;
  isShow = true;

  totalItems: number;
  currentPage: number = 1;
  itemsPerPage: number = 12;
  tableData: any;
  searchData = '';
  operateId: number;


  @ViewChild('deleteModal') public deleteModal: ModalDirective;
  constructor(private httpService: HttpService) { }

  ngOnInit() {
    this.getArticleList(1,this.itemsPerPage,'')
  }

  //获取文章列表
  getArticleList(page: number,pageSize: number,title: string){
    const url = `${adSystemApiUrl}/v1/admin/posts/list?page=${page}&pageSize=${pageSize}&title=${title}`;
    return this.httpService.httpGetAuth(url)
      .subscribe(
        data => {
          this.totalItems = data.data.total;
          this.currentPage = data.data.current_page;
          this.tableData = data.data.data;
        }
      )
  }

  //搜索
  search(){
    this.getArticleList(1,this.itemsPerPage,this.searchData);
  }
  reset(){
    this.searchData = '';
    this.getArticleList(1,this.itemsPerPage,'');
  }

  //翻页
  pageChanged(event: any): void {
    window.scrollTo(0,0);
    this.getArticleList(event.page, event.itemsPerPage,this.searchData);
  }

  // 删除文章
  delDialog(id: number) {
    this.operateId = id;
    this.deleteModal.show();
  }
  delArtical() {
    const url = `${adSystemApiUrl}/v1/admin/posts/del?id=${this.operateId}`;
    return this.httpService.httpPostAuth(url, {}).subscribe(
      res => {
        if (res.code === 2000) {
          this.deleteModal.hide();
          this.type = 'success';
          this.message = '文章删除成功';
          this.isShow = true;
          this.getArticleList(1, this.itemsPerPage, this.searchData);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }
}
